/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package perl;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.*;
import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import view.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Cette classe qui hérite la classe JFrame construit la fenêtre principale de l'application.
 * @author NGUYEN Dac Cong Tai
 */
public class PerlView extends JFrame implements ActionListener{
    private Fond mainPanel;
    private Fond viewPanel;
    private JScrollPane scrollPane;
    private JMenuBar menuBar;
    private String url;
    private ArrayList<Element> listBriques;
    private JMenu menuBrick;
    private String codeLangue;
    private String user;
    private Element root;
    private String typeProfil;

    /**
     * Constructeur avec 4 paramètres.
     * @param element l'élément contenant des informations d'application
     * @param chemin le chemin du profil
     * @param langue le langage d'affichage
     * @param utilisateur l'utilisateur
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public PerlView(Element element, String chemin, String langue, String utilisateur) throws ParserConfigurationException, SAXException, IOException {
        try {
            this.url = chemin;
            this.user = utilisateur;
            this.codeLangue = langue;
            this.root = element;
            Element principal = (Element) root.getElementsByTagName("FPrincipale").item(0);
            String caption = ((Element)principal.getElementsByTagName("Caption").item(0)).getElementsByTagName(langue).item(0).getTextContent();
            setTitle(caption+" - "+utilisateur/*+" ("+url.substring(url.lastIndexOf("\\")+1,url.length())+")"*/);

            setIconImage(Toolkit.getDefaultToolkit().getImage(Utility.getPath(this,"/Fichiers systeme/Images/visualisation.png")));
            initComponents(principal);
            voirProfil(principal);
        } catch (Exception e){
            Element principal = (Element) root.getElementsByTagName("FPrincipale").item(0);
            String error = ((Element)principal.getElementsByTagName("Erreur").item(0)).getElementsByTagName(langue).item(0).getTextContent();
            JOptionPane.showMessageDialog(this,
                    ((Element)principal.getElementsByTagName("MessageErreur").item(0)).getElementsByTagName(langue).item(0).getTextContent()+"\n"+error+": "+e.getMessage(),
                    error,
                    JOptionPane.ERROR_MESSAGE);
            Utility.exit();
        }
    }

    /**
     * Initialise la fenêtre.
     * @param element l'élément contenant des informations d'application
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    private void initComponents(Element element) throws ParserConfigurationException, SAXException, IOException{
        mainPanel=new Fond(Toolkit.getDefaultToolkit().getImage(Utility.getPath(this,"/Fichiers systeme/Images/ImageFond1.jpg")));
        viewPanel = new Fond(Toolkit.getDefaultToolkit().getImage(Utility.getPath(this,"/Fichiers systeme/Images/ImageFond.jpg")));
        menuBar = new JMenuBar();

        Dimension ecran = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(ecran.width, ecran.height-30));

        //mainPanel.setBackground(new Color(250, 230, 230));
        mainPanel.setName("mainPanel");
        getContentPane().add(mainPanel,"North");

        viewPanel.setLayout(new GridBagLayout());
        viewPanel.setBorder(null);

        scrollPane = new JScrollPane(viewPanel);
        scrollPane.setBorder(null);
        getContentPane().add(scrollPane);
        setJMenuBar(menuBar);

        JMenu menuFile = new JMenu();
        menuFile.setText(((Element)element.getElementsByTagName("Fichier1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent());

        menuBar.add(menuFile);
        Utility.addMenuItem(this, menuFile, ((Element)element.getElementsByTagName("Ouvrir1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent(), "ouvrir", KeyEvent.VK_O, true);
        menuFile.addSeparator();
        Utility.addMenuItem(this, menuFile, ((Element)element.getElementsByTagName("Proprietes1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent(), "propriete", KeyEvent.VK_P, true);
        menuFile.addSeparator();
        Utility.addMenuItem(this, menuFile, ((Element)element.getElementsByTagName("Quiter1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent(), "quitter", KeyEvent.VK_Q, true);

        menuBrick = new JMenu();
        menuBrick.setText(((Element)element.getElementsByTagName("MBrique").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent());
        menuBar.add(menuBrick);

        JMenu menuHelp = new JMenu();
        menuHelp.setText(((Element)element.getElementsByTagName("Aide1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent());
        menuBar.add(menuHelp);
        Utility.addMenuItem(this, menuHelp, ((Element)element.getElementsByTagName("Aide1").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent(), "aide", KeyEvent.VK_F1, true);
        //setLocationRelativeTo(null);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        //setVisible(true);
    }

    /**
     * Traite des informations du profil.
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public void voirProfil(Element element) throws ParserConfigurationException, SAXException, IOException{
        Element rootEl = Utility.getElement(this.url);
        listBriques = new ArrayList<Element>();

        Element listEleves = (Element) rootEl.getElementsByTagName("groupe").item(0);
        if(listEleves!=null){
            typeProfil="Groupe";
	    JLabel nomGrp = new JLabel("<html>"+listEleves.getAttribute("nom"));
            nomGrp.setFont(new Font("Bradley Hand ITC",1,30));
            mainPanel.add(nomGrp);
            //TO DO
        }else {
            typeProfil="Eleve";
            String nom = rootEl.getAttribute("nom_eleve")+" "+rootEl.getAttribute("prenom_eleve");
            JLabel nomEtu = new JLabel("<html>"+nom);
            nomEtu.setFont(new Font("Bradley Hand ITC",1,30));
            mainPanel.add(nomEtu);
        }

        Dimension ecran = Toolkit.getDefaultToolkit().getScreenSize();
        NodeList nodeListBriques = rootEl.getElementsByTagName("brique");
        Element vues = (Element) root.getElementsByTagName("FVues").item(0);
        GridBagConstraints c = new GridBagConstraints();
        
        c.weightx=0.0;
        c.gridy = 0;
        c.gridx = 0;
        String moyen = ((Element)element.getElementsByTagName("Moyenne").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent();
        String sum = ((Element)element.getElementsByTagName("Somme").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent();
        String value = ((Element)element.getElementsByTagName("Valeur").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent();
        for(int i=0; i<nodeListBriques.getLength();i++){
            Element brique = (Element) nodeListBriques.item(i);
            
            listBriques.add(brique);
            String nomBrique = brique.getAttribute("nom");
            int type = Integer.parseInt(brique.getAttribute("type"));
            JMenu menu = new JMenu();
            if(nomBrique.equals(null) || nomBrique.equals("")){
                Utility.addMenuItem(this, menuBrick, ((Element)element.getElementsByTagName("Texte").item(0)).getElementsByTagName(codeLangue).item(0).getTextContent(), Integer.toString(i), -1, true);
            } else {
                menu.setText(nomBrique);
                menuBrick.add(menu);
            }
            
            switch(type){
                case 0:
                    ListeView lv = new ListeView(brique, ecran, vues, codeLangue, typeProfil);
                    viewPanel.add(lv,c);
                    for (int a=0; a<lv.getTypeOperations().size(); a++){
                        JMenu menuTmp = new JMenu(value+(a+1));
                        menu.add(menuTmp);
                        lv.getListMenuVal().add(menuTmp);
                        Utility.addMenuItem(lv, menuTmp, moyen, a+",0", -1, false);
                        Utility.addMenuItem(lv, menuTmp, sum, a+",1", -1, true);
                    }
                    break;
                case 1:
                    RepartitionView rv = new RepartitionView(listBriques.get(i),ecran, vues, codeLangue, typeProfil);
                    viewPanel.add(rv,c);
                    for (int a=0; a<rv.getTypeOperations().size(); a++){
                        JMenu menuTmp = new JMenu(value+(a+1));
                        menu.add(menuTmp);
                        rv.getListMenuVal().add(menuTmp);
                        Utility.addMenuItem(rv, menuTmp, moyen, a+",0", -1, false);
                        Utility.addMenuItem(rv, menuTmp, sum, a+",1", -1, true);
                    }
                    break;
                case 2:
                    GrapheView gv = new GrapheView(listBriques.get(i),ecran, vues, codeLangue, typeProfil);
                    viewPanel.add(gv,c);
                    for (int a=0; a<gv.getTypeOperations().size(); a++){
                        JMenu menuTmp = new JMenu(value+(a+1));
                        menu.add(menuTmp);
                        gv.getListMenuVal().add(menuTmp);
                        Utility.addMenuItem(gv, menuTmp, moyen, a+",0", -1, false);
                        Utility.addMenuItem(gv, menuTmp, sum, a+",1", -1, true);
                    }
                    break;
                case 3:
                    CommentaireView cv = new CommentaireView(listBriques.get(i),ecran, vues, codeLangue);
                    viewPanel.add(cv,c);
                    break;
            }

            if(c.gridx==2){
                c.gridx =0;
                c.gridy++;
            } else {
                c.gridx ++;
            }
        }
    }

    /**
     * Définit les actions.
     * @param e l'action
     */
    public void actionPerformed(ActionEvent e) {
        String c = e.getActionCommand();
        if (c.equals("quitter")) {
            Utility.exit();
        } else if(c.equals("ouvrir")){
            JFileChooser jfc = Utility.ouvrirOpenBox(url,null);
            if(jfc!=null){
                String chemin = jfc.getSelectedFile().getAbsolutePath();
                dispose();
                try {
                    App.getApplication().show(new PerlView(this.root,chemin,this.codeLangue, this.user));
                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(PerlApp.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SAXException ex) {
                    Logger.getLogger(PerlApp.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(PerlApp.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else if(c.equals("propriete")){
            try {
                App.getApplication().show(new PerlProperties(root, url, codeLangue, typeProfil));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(PerlView.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (c.equals("aide")){
            //TO DO
        }
    }
}
